package com.wanxi.service.impl;

import com.wanxi.dao.NavDao;
import com.wanxi.dao.impl.NavDaoImpl;
import com.wanxi.dto.ResultDTO;
import com.wanxi.model.NavModel;
import com.wanxi.service.NavService;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

public class NavServiceImpl implements NavService {
    private NavDao navDao = new NavDaoImpl();

    @Override
    public ResultDTO getNavListModel() {
        /**
         * 1.判断redis是否存在
         * 2.存在在取值，然后封装到list
         * 3.不存在，则取数据库，然后存入redis
         */
        Jedis jedis = new Jedis();
        boolean isHave = jedis.exists("hrefs");
        List<NavModel> list = new ArrayList<>();
        if (isHave) {
//            如果是-1，则全部拿到
            List<String> hrefs = jedis.lrange("hrefs", 0, -1);
            List<String> names = jedis.lrange("names", 0, -1);
            for (int i = 0; i < hrefs.size(); i++) {
                list.add(NavModel.builder()
                        .name(names.get(i))
                        .href(hrefs.get(i))
                        .build());
            }
        } else {

            list = navDao.getNavListModel();
            for (NavModel model : list) {
                jedis.rpush("hrefs", model.getHref());
                jedis.rpush("names", model.getName());
            }
        }

        return ResultDTO.builder()
                .data(list)
                .build();
    }

    public ResultDTO add(NavModel navModel) {
        int count = navDao.add(navModel);
        if (count > 0) {
            Jedis jedis = new Jedis();
            jedis.del("hrefs", "names");
        }
        return ResultDTO.builder()
                .count(count)
                .build();
    }
}
